#include "pch.h"

#include "core/factory.h"
#include "core/referencecount.h"
#include "core/rtti.h"



namespace Core
{

	Factory * Factory::Singleton = 0;





	///
	Factory * Factory::Instance()
	{
		if(Singleton == 0)
		{
			Singleton = r_new(Factory);
		}

		return Singleton;
	}


	///
	void Factory::Destroy()
	{
		if(Singleton != 0)
		{
			r_delete(Singleton);
		}

		Singleton = 0;
	}





	///
	Factory::Factory():
	m_names(512)
	{

	}


	///
	Factory::~Factory()
	{

	}


	///
	void Factory::Register(const Core::Rtti *rtti, const Helper::String &name, const Helper::FCC &fcc)
	{
		if(this->ClassExists(name))
			return;

		if(this->ClassExists(fcc))
			return;

		this->m_names.Add(name, rtti);
		this->m_fccs.Add(fcc, rtti);
	}


	///
	bool Factory::ClassExists(const Helper::String & name) const 
	{
		return this->m_names.Contains(name);
	}


	///
	bool Factory::ClassExists(const Helper::FCC fcc) const
	{
		return this->m_fccs.Contains(fcc);
	}


	///
	const Rtti * Factory::GetClassRtti(const Helper::FCC &fcc) const
	{
		return this->m_fccs[fcc];
	}


	///
	const Rtti * Factory::GetClassRtti(const Helper::String &name) const
	{
		return this->m_names[name];
	}


	///
	ReferenceCount * Factory::Create(const Helper::FCC fcc) const
	{
		if(!this->ClassExists(fcc))
			return NULL;

		const Rtti * rtti = this->m_fccs[fcc];

		ReferenceCount * obj = rtti->Create();

		return obj;
	}


	///
	ReferenceCount * Factory::Create(const Helper::String &name) const
	{
		if(!this->ClassExists(name))
			return NULL;

		const Rtti * rtti = this->m_names[name];

		ReferenceCount * obj = rtti->Create();

		return obj;
	}


}